package comxin.demo1.jdbcdemo;

import comxin.demo1.Utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*
      演示Statement出现的的sql注入问题
      输入账号密码是一个方法
      验证是一个方法
 */
public class sqldemo_01 {
    public static void main(String[] args) {
        //初始化登录界面
        Map<String,String> userLogininfo=initUI();
        //验证登录
        boolean loginSuccess=logein(userLogininfo);
        //输出结果
        System.out.println(loginSuccess?"登录成功":"登录失败");
    }
    /*
           用户登录
     */
    public static Map<String, String> initUI() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入账号");
        String id = scanner.nextLine();
        System.out.println("请输入密码");
        String  password = scanner.nextLine();
        Map<String, String> initmap = new HashMap<>();
        initmap.put("username", id);
        initmap.put("password", password);
        return initmap;
    }
    /*
          验证登录
     */

    public static boolean logein(Map<String,String> userLogininfo) {
        boolean loginSuccess=false;
        Connection conn=null;
        Statement sta=null;
        ResultSet re=null;
        conn=JdbcUtils.getConnection();
        try {
            sta=conn.createStatement();
            String sql1=
                    "select * from idpassword where username='"+userLogininfo.get("username")+
                            "' and password='"+userLogininfo.get("password")+"'";
            re=sta.executeQuery(sql1);
            if (re.next()){
                loginSuccess=true;
            }
            return loginSuccess;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn,sta,re);
        }
        return false;
    }
}
